<?php

/**
 * 用户模型
 */

namespace app\api\model;


use app\api\controller\Bind;
use app\api\controller\Config;
use app\common\lib\RedisKey;
use app\common\lib\RespCode;
use app\common\model\BaseModel;
use custom\Err;
use custom\Log;
use custom\Redis;
use custom\Token;
use oss\Oss;
use PDOStatement;
use think\Db;
use think\db\exception\DataNotFoundException;
use think\db\exception\ModelNotFoundException;
use think\Exception;
use think\exception\DbException;
use think\exception\PDOException;
use think\Model;

class HousePoster extends BaseModel {

    /**
     * 生成小程序三方接口
     */
    const http_TYPE=[
        'A'=>"https://api.weixin.qq.com/wxa/getwxacode",//名片二维码
        'B'=>"https://api.weixin.qq.com/wxa/getwxacodeunlimit",//房源详情分享二维码
        'C'=>"https://api.weixin.qq.com/wxa/getwxacode",//房源清单分享二维码
    ];


    /**
     * 生成二维码
     */
    public  function createWechatCode($company_id=0, $agent_id=0,$house_id=0,$page='',$type='A',$name='',$city_code=0,$area_code=0) {
        $url = '';
        //获取小程序配置
        $company=db('company')->field('appid,secret')->where("id={$company_id} and deleted=0")->find();
        $appid = $company['appid'];
        $secret = $company['secret'];
        $grant_type = 'client_credential';
       //小程序接口调用凭证获取
        $access_token = "https://api.weixin.qq.com/cgi-bin/token?grant_type={$grant_type}&appid={$appid}&secret={$secret}";
        $json = self::httpRequest($access_token);
        $json = json_decode($json, true);
        if (!isset($json['access_token'])) {
            return false;
        }
        //组装请求
        $ACCESS_TOKEN = $json["access_token"];
        $http_type=self::http_TYPE[$type];
        $qcode = $http_type."?access_token={$ACCESS_TOKEN}";
        $param=$this->wechatUrl($page,$type,$agent_id,$house_id,$city_code,$area_code);

        $result = self::httpRequest($qcode, $param, "POST");//文件流
        $oss = Oss::getInstance();
        $path="moblie/createWechatCode/{$company_id}/{$name}";
        if(config('global.dev') == 'dev'){
            $path="test/moblie/createWechatCode/{$company_id}/{$name}";
        }
        $url = $oss->posterFilename($path, 'jpeg');
        if ($oss->putObject($result)) {
            $this->setRedis($agent_id,$house_id,$city_code,$area_code,$url,$type);
        }
        return $url;
    }

    /**
     * http请求
     * @param $url
     * @param string $data
     * @param string $method
     * @return bool|string
     */
    public static function httpRequest($url, $data = '', $method = 'GET') {
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
        curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
        curl_setopt($curl, CURLOPT_USERAGENT, $_SERVER['HTTP_USER_AGENT']);
        curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($curl, CURLOPT_AUTOREFERER, 1);
        if ($method == 'POST') {
            curl_setopt($curl, CURLOPT_POST, 1);
            if ($data != '') {
                curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
            }
        }
        curl_setopt($curl, CURLOPT_TIMEOUT, 30);
        curl_setopt($curl, CURLOPT_HEADER, 0);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        $result = curl_exec($curl);
        curl_close($curl);
        return $result;
    }

    public function wechatUrl($page='',$type='A',$agent_id=0,$house_id=0,$city_code=0,$area_code=0){
        switch ($type){
            case 'A':
                $param = json_encode(array("path" => "{$page}?agent_id={$agent_id}", "width" => 150));
            break;
            case 'B':
                $param = json_encode(array("page" => "{$page}","scene"=>"agent_id={$agent_id}&id={$house_id}&is_re=1", "width" => 150));
            break;
            case 'C':
            $param = json_encode(array("path" => "{$page}?agent_id={$agent_id}&city_code={$city_code}&area_code={$area_code}", "width" => 150));
            break;
            default:
            break;
        }

        return $param;
    }

    public function setRedis($agent_id=0,$house_id=0,$city_code=0,$area_code=0,$url='',$type='A'){
        $redisModel = Redis::getInstance();
        if ($type=='B'){
            $key_code=RedisKey::HOUSE_WECHAT_CODE;//redis 对应 hash表
            $redisModel->hset($key_code, $agent_id."_".$house_id, $url);
        }
        if ($type=='C'){
            $key_code=RedisKey::HOUSE_DETAILED_WECHAT_CODE;//redis 对应 hash表
            $redisModel->hset($key_code, $agent_id."_".$city_code."_".$area_code, $url);
        }




    }
}
